package cn.stylefeng.guns.modular.demo.service;

import cn.stylefeng.guns.core.exception.BusinessException;
import cn.stylefeng.guns.core.exception.BusinessExceptionEnum;
import cn.stylefeng.guns.dao.IGaiaProductBusinessService;
import cn.stylefeng.guns.dao.IGoodsService;
import cn.stylefeng.guns.dao.ISaleStockService;
import cn.stylefeng.guns.dao.IWholesaleSalesRecordService;
import cn.stylefeng.guns.dao.entity.*;
import cn.stylefeng.guns.dao.impl.GaiaWmsStockHServiceImpl;
import cn.stylefeng.guns.dao.mapper.GaiaWmsDiaoboMMapper;
import cn.stylefeng.guns.dao.mapper.yaode.GaiaSdSaleDMapper;
import cn.stylefeng.guns.dao.service.*;
import cn.stylefeng.guns.modular.demo.controller.domain.QueryWarehouseStockRequest;
import cn.stylefeng.guns.modular.demo.controller.domain.StatisticsSaleStockRequest;
import cn.stylefeng.guns.modular.demo.controller.domain.StatisticsSaleStockV3Request;
import cn.stylefeng.guns.modular.demo.enums.SaleStockTypeEnum;
import cn.stylefeng.guns.util.RebateDateUtil;
import cn.stylefeng.roses.kernel.system.modular.user.service.SysUserRoleService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Table;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SaleStockBizService {


    @Resource
    private ISaleStockService saleStockService;

    @Resource
    private IGoodsService goodsService;


    @Resource
    private IGaiaWmsKucenService gaiaWmsKucenService;
    @Resource
    private IWholesaleSalesRecordService wholesaleSalesRecordService;
    @Resource
    private IGaiaBatchInfoService gaiaBatchInfoService;
    @Autowired
    private GaiaWmsDiaoboMMapper gaiaWmsDiaoboMMapper;
    @Resource
    private IGaiaSdSalePayMsgService gaiaSdSalePayMsgService;
    @Resource
    private IGaiaProductBusinessService gaiaProductBusinessService;
    @Resource
    private IUserRelationService userRelationService;
    @Resource
    private SysUserRoleService sysUserRoleService;
    @Resource
    private IGaiaWmsStockHService gaiaWmsStockHService;
    @Resource
    private IGaiaSdStockBatchHService gaiaSdStockBatchHService;


    @Resource
    private GaiaSdSaleDMapper gaiaSdSaleDMapper;

    @NotNull
    public StatisticsSaleStockVO getStatisticsSaleStockVO(StatisticsSaleStockRequest statisticsSaleStockRequest) {
        String batchNo = statisticsSaleStockRequest.getBatchNo();
        StatisticsSaleStockVO statisticsSaleStockVO = new StatisticsSaleStockVO();
        statisticsSaleStockVO.setPurchaseAmount(getPurchaseAmount(batchNo));
        GaiaBatchInfo gaiaBatchInfo = gaiaBatchInfoService.getOne(Wrappers.<GaiaBatchInfo>lambdaQuery().eq(GaiaBatchInfo::getBatBatch, batchNo));
        if (Objects.isNull(gaiaBatchInfo)) {
            throw new BusinessException(BusinessExceptionEnum.BATCH_NOT_EXIST);
        }
        statisticsSaleStockVO.setPurchaseAmount4Supplier(gaiaBatchInfo.getBatReceiveQty());

        statisticsSaleStockVO.setSaleAmount(getSaleAmount(batchNo));
        statisticsSaleStockVO.setSaleAmount4Supplier(getSaleAmount4Supplier(batchNo));

        String batProCode = gaiaBatchInfo.getBatProCode();
        Goods goods = goodsService.getOne(Wrappers.<Goods>lambdaQuery().eq(Goods::getCommodityCode, batProCode));
        statisticsSaleStockVO.setGoodsCode(goods.getCommodityCode());
        statisticsSaleStockVO.setGoodsName(goods.getCommodityName());

        statisticsSaleStockVO.setStockAmount(getStockAmount(batchNo));
        statisticsSaleStockVO.setStockAmountForSupplier(getStockAmount4Supplier(batchNo));


        statisticsSaleStockVO.setWholesaleSalesAmount(gaiaWmsDiaoboMMapper.queryDiaoBoByBatch(batchNo));
        List<WholesaleSalesRecord> list = wholesaleSalesRecordService.list(Wrappers.<WholesaleSalesRecord>lambdaQuery().eq(WholesaleSalesRecord::getBatchNo, batchNo));
        int sum = list.stream().map(WholesaleSalesRecord::getUsedNum).mapToInt(r -> r).sum();
        int totalNum = list.stream().map(WholesaleSalesRecord::getTotalNum).mapToInt(r -> r).sum();
        statisticsSaleStockVO.setWholesaleSalesUsedAmount(sum);
        statisticsSaleStockVO.setWholesaleSalesUnallocatedAmount(totalNum - sum);
        return statisticsSaleStockVO;
    }

    @NotNull
    public StatisticsSaleStockVO getStatisticsSaleStockVOByTime(StatisticsSaleStockRequest statisticsSaleStockRequest) {
        StatisticsSaleStockVO statisticsSaleStockVO = new StatisticsSaleStockVO();
        Long startTime = statisticsSaleStockRequest.getStartTime();
        Long endTime = statisticsSaleStockRequest.getEndTime();
        String startTimeStr = RebateDateUtil.format(startTime);
        String endTimeStr = RebateDateUtil.format(endTime);


        statisticsSaleStockVO.setPurchaseAmount(gaiaSdSaleDMapper.getPurchaseAmount(startTimeStr, endTimeStr));
//        GaiaBatchInfo gaiaBatchInfo = gaiaBatchInfoService.getOne(Wrappers.<GaiaBatchInfo>lambdaQuery().eq(GaiaBatchInfo::getBatBatch, batchNo));
//        if (Objects.isNull(gaiaBatchInfo)) {
//            throw new BusinessException(BusinessExceptionEnum.BATCH_NOT_EXIST);
//        }

        statisticsSaleStockVO.setPurchaseAmount4Supplier(getPurchaseAmountBytime(startTime, endTime));
//
        statisticsSaleStockVO.setSaleAmount(gaiaSdSaleDMapper.getSaleAmount(startTimeStr, endTimeStr));
        statisticsSaleStockVO.setSaleAmount4Supplier(getSaleAmount4Supplier(startTime, endTime));
//
//        String batProCode = gaiaBatchInfo.getBatProCode();
//        Goods goods = goodsService.getOne(Wrappers.<Goods>lambdaQuery().eq(Goods::getCommodityCode, batProCode));
//        statisticsSaleStockVO.setGoodsCode(goods.getCommodityCode());
//        statisticsSaleStockVO.setGoodsName(goods.getCommodityName());
//
        statisticsSaleStockVO.setStockAmount(getStockAmount(null));
        statisticsSaleStockVO.setStockAmountForSupplier(getStockAmount4Supplier(null));
//
//
        statisticsSaleStockVO.setWholesaleSalesAmount(gaiaSdSaleDMapper.getWholesaleSalesAmount(startTimeStr, endTimeStr));
        List<WholesaleSalesRecord> list = wholesaleSalesRecordService.list();
        int sum = list.stream().map(WholesaleSalesRecord::getUsedNum).mapToInt(r -> r).sum();
        int totalNum = list.stream().map(WholesaleSalesRecord::getTotalNum).mapToInt(r -> r).sum();
        statisticsSaleStockVO.setWholesaleSalesUsedAmount(sum);
        statisticsSaleStockVO.setWholesaleSalesUnallocatedAmount(totalNum - sum);
        return statisticsSaleStockVO;
    }

//    /**
//     * 统计每个门店库存
//     *
//     * @return
//     */
//    public IPage getChainStock(String stoCode, String time) {
//
//        Long lastDayBegin = RebateDateUtil.getLastDayBegin(1);
//        Long lastDayEnd = RebateDateUtil.getLastDayEnd(1);
//
//
//        QueryWrapper<SaleStock> queryWrapper = Wrappers.<SaleStock>query().select("goods_id,batch_no,sum(\n" +
//                "case \n" +
//                "when sale_type=2 and type ='supplier' then -num \n" +
//                "when sale_type=1 and type ='supplier' then num \n" +
//                "when sale_type=2 and type ='SY' then num \n" +
//                "when sale_type=1 and type ='SY' then -num\n" +
//                "when sale_type=1 and type ='SY' then -num\n" +
//                "when  type ='BD' then -num\n" +
//                "end\n" +
//                "  ) as num");
//        queryWrapper.eq("sto_code", stoCode);
//
//        queryWrapper.between("sale_time", lastDayBegin, lastDayEnd)
//                .groupBy("goods_id,batch_no")
//                .orderByAsc("goods_id");
//        page = saleStockService.page(page, Wrappers.<SaleStock>lambdaQuery().eq(SaleStock::getSaleId, 1));
//        long total = page.getTotal();
//        if (total == 0) {
//            return page;
//        }
//        List<SaleStock> records = page.getRecords();
//        Map<String, Goods> goodsMap = goodsService.listByIds(records.stream().map(SaleStock::getGoodsId).collect(Collectors.toList()))
//                .stream().collect(Collectors.toMap(Goods::getGoodsId, Function.identity()));
//        // 连锁库存
//        List<GaiaWmsStockH> gaiaWmsStockHList = gaiaWmsStockHService.list(Wrappers.<GaiaWmsStockH>lambdaQuery()
//                .in(GaiaWmsStockH::getProCode, goodsMap.get(goodsId).getCommodityCode())
//                .eq(GaiaWmsStockH::getProSite, "100")
//                .eq(GaiaWmsStockH::getBatch, batchNo)
//                .eq(GaiaWmsStockH::getStockMonth, month)
//                .eq(GaiaWmsStockH::getStockYear, year));
//
//        List<SaleStock> records = stockPage.getRecords();
//        for (SaleStock record : records) {
//            String type = record.getType();
//            Integer num = record.getNum();
//            String stoCode = record.getStoCode();
//            String batchNo = record.getBatchNo();
//            String goodsId = record.getGoodsId();
//
//
//        }
//
//        // 连锁库存
//        List<GaiaWmsStockH> gaiaWmsStockHList = gaiaWmsStockHService.list(Wrappers.<GaiaWmsStockH>lambdaQuery().in(GaiaWmsStockH::getProCode, goodsCodeList).in(CollectionUtils.isNotEmpty(storeCodeList), GaiaWmsStockH::getProSite, storeCodeList).eq(GaiaWmsStockH::getStockMonth, RebateDateUtil.formatMonth(startTime)).eq(GaiaWmsStockH::getStockYear, RebateDateUtil.formatYear(startTime)));
//        Map<String, Double> goodsStockMap = gaiaWmsStockHList.stream().collect(Collectors.toMap(GaiaWmsStockH::getProCode, GaiaWmsStockH::getTotalQty));
//        //门店库存
//        QueryWrapper<GaiaSdStockBatchH> queryWrapper = Wrappers.<GaiaSdStockBatchH>query().select("gssb_pro_id,sum(gssb_qty) as gssb_qty").in("gssb_pro_id", goodsCodeList).eq("mat_assess_month", RebateDateUtil.formatMonth(startTime)).eq("mat_assess_year", RebateDateUtil.formatYear(startTime)).groupBy("gssb_pro_id");
//        if (CollectionUtils.isNotEmpty(storeCodeList)) {
//            queryWrapper.in("gssb_br_id", storeCodeList);
//        }
//        List<GaiaSdStockBatchH> gaiaSdStockBatchHList = gaiaSdStockBatchHService.list(queryWrapper);
//        Map<String, Double> batchStockMap = gaiaSdStockBatchHList.stream().collect(Collectors.toMap(GaiaSdStockBatchH::getGssbProId, GaiaSdStockBatchH::getGssbQty));
//
//        log.info("统计数据 saleStockList={}", JSON.toJSONString(page));
//        return page;
//    }
//
//    private void calStock(IPage<SaleStock> stockPage) {
//
//        long total = stockPage.getTotal();
//        if (total == 0) {
//            return;
//        }
//        Long lastDayEnd = RebateDateUtil.getLastDayEnd(1);
//        String month = RebateDateUtil.formatMonth(lastDayEnd);
//        String year = RebateDateUtil.formatYear(lastDayEnd);
//        List<SaleStock> records = stockPage.getRecords();
//        Map<String, Goods> goodsMap = goodsService.listByIds(records.stream().map(SaleStock::getGoodsId).collect(Collectors.toList()))
//                .stream().collect(Collectors.toMap(Goods::getGoodsId, Function.identity()));
//
//        for (SaleStock record : records) {
//            String type = record.getType();
//            Integer num = record.getNum();
//            String stoCode = record.getStoCode();
//            String batchNo = record.getBatchNo();
//            String goodsId = record.getGoodsId();
//            if (Objects.equals(stoCode, "100")) {
//                // 连锁库存
//                List<GaiaWmsStockH> gaiaWmsStockHList = gaiaWmsStockHService.list(Wrappers.<GaiaWmsStockH>lambdaQuery()
//                        .in(GaiaWmsStockH::getProCode, goodsMap.get(goodsId).getCommodityCode())
//                        .eq(GaiaWmsStockH::getProSite, "100")
//                        .eq(GaiaWmsStockH::getBatch, batchNo)
//                        .eq(GaiaWmsStockH::getStockMonth, month)
//                        .eq(GaiaWmsStockH::getStockYear, year));
//                if (!CollectionUtils.isEmpty(gaiaWmsStockHList)) {
//                    GaiaWmsStockH gaiaWmsStockH = gaiaWmsStockHList.get(0);
//                    num = num += Optional.ofNullable(gaiaWmsStockH).map(GaiaWmsStockH::getTotalQty).orElse(0D).intValue();
//                }
//                WholesaleSalesRecord one = wholesaleSalesRecordService.getOne(Wrappers.<WholesaleSalesRecord>lambdaQuery()
//                        .eq(WholesaleSalesRecord::getBatchNo, batchNo)
//                        .eq(WholesaleSalesRecord::getProCode, goodsMap.get(goodsId).getCommodityCode()));
//                num = num += Optional.ofNullable(one).map(z -> z.getTotalNum() - z.getUsedNum()).orElse(0);
//
//
//            } else {
//                GaiaSdStockBatchH one = gaiaSdStockBatchHService.getOne(Wrappers.<GaiaSdStockBatchH>lambdaQuery()
//                        .eq(GaiaSdStockBatchH::getGssbProId, goodsMap.get(goodsId).getCommodityCode())
//                        .eq(GaiaSdStockBatchH::getGssbBrId, stoCode)
//                        .eq(GaiaSdStockBatchH::getMatAssessMonth, month)
//                        .eq(GaiaSdStockBatchH::getGssbBatch, batchNo)
//                        .eq(GaiaSdStockBatchH::getMatAssessYear, year));
//                num = num += Optional.ofNullable(one).map(GaiaSdStockBatchH::getGssbQty).orElse(0D).intValue();
//            }
//
//        }
//    }


    @NotNull
    public IPage<SaleStockStatisticsVO> getStatisticsStatisticsSaleStockV3Request(StatisticsSaleStockV3Request saleStockV3Request) {
        List<String> goodsIdList = saleStockV3Request.getGoodsIdList();
        Long endTime = saleStockV3Request.getEndTime();
        Long startTime = saleStockV3Request.getStartTime();
        List<String> storeCodeList = saleStockV3Request.getStoreCodeList();
        IPage page = new Page<>();
        page.setCurrent(saleStockV3Request.getPageNo());
        page.setSize(saleStockV3Request.getPageSize());
        log.info("开始进来了吗");

        page = goodsService.page(page, Wrappers.<Goods>lambdaQuery().in(CollectionUtils.isNotEmpty(goodsIdList), Goods::getGoodsId, goodsIdList).orderByAsc(Goods::getGoodsId));
        List<Goods> goodsList = page.getRecords();
        List<String> queryGoodsIdList = goodsList.stream().map(Goods::getGoodsId).collect(Collectors.toList());


        List<SaleStock> saleStockList = getSaleStocks(queryGoodsIdList, storeCodeList, startTime, endTime);

        Map<String, Goods> goodsMap = goodsList.stream().collect(Collectors.toMap(Goods::getGoodsId, Function.identity()));
        List<String> goodsCodeList = goodsMap.values().stream().map(Goods::getCommodityCode).collect(Collectors.toList());
        //goodsId,type,num
        HashBasedTable<String, String, Integer> stockTable = HashBasedTable.create();
        saleStockList.forEach(r -> {
            stockTable.put(r.getGoodsId(), r.getType(), r.getNum());
        });
        //计算期初
        Long firstDayOfMonth = RebateDateUtil.getFirstDayOfMonth(startTime);
        QueryWrapper<SaleStock> queryWrapperBegin = Wrappers.<SaleStock>query().select("goods_id,sum(if(sale_type=1,-num,num)) as num");
        queryWrapperBegin.in("goods_id", goodsList);
        if (CollectionUtils.isNotEmpty(storeCodeList)) {
            queryWrapperBegin.in("sto_code", storeCodeList);
        }
        queryWrapperBegin.between("sale_time", firstDayOfMonth, startTime).groupBy("goods_id").orderByAsc("goods_id");
        List<SaleStock> begainList = saleStockService.list(queryWrapperBegin);
        Map<String, Integer> begainMap = begainList.stream().collect(Collectors.toMap(SaleStock::getGoodsId, SaleStock::getNum));

//        // 连锁库存
        List<GaiaWmsStockH> gaiaWmsStockHList = gaiaWmsStockHService.list(Wrappers.<GaiaWmsStockH>lambdaQuery().in(GaiaWmsStockH::getProCode, goodsCodeList).in(CollectionUtils.isNotEmpty(storeCodeList), GaiaWmsStockH::getProSite, storeCodeList).eq(GaiaWmsStockH::getStockMonth, RebateDateUtil.formatMonth(startTime)).eq(GaiaWmsStockH::getStockYear, RebateDateUtil.formatYear(startTime)));
        Map<String, Double> goodsStockMap = gaiaWmsStockHList.stream().collect(Collectors.toMap(GaiaWmsStockH::getProCode, GaiaWmsStockH::getTotalQty));
        //门店库存
        QueryWrapper<GaiaSdStockBatchH> queryWrapper = Wrappers.<GaiaSdStockBatchH>query().select("gssb_pro_id,sum(gssb_qty) as gssb_qty").in("gssb_pro_id", goodsCodeList).eq("mat_assess_month", RebateDateUtil.formatMonth(startTime)).eq("mat_assess_year", RebateDateUtil.formatYear(startTime)).groupBy("gssb_pro_id");
        if (CollectionUtils.isNotEmpty(storeCodeList)) {
            queryWrapper.in("gssb_br_id", storeCodeList);
        }
        List<GaiaSdStockBatchH> gaiaSdStockBatchHList = gaiaSdStockBatchHService.list(queryWrapper);
        Map<String, Double> batchStockMap = gaiaSdStockBatchHList.stream().collect(Collectors.toMap(GaiaSdStockBatchH::getGssbProId, GaiaSdStockBatchH::getGssbQty));

        List<SaleStockStatisticsVO> saleStockStatisticsVOS = goodsList.stream().map(r -> {
            SaleStockStatisticsVO saleStockStatisticsVO = new SaleStockStatisticsVO();
            Map<String, Integer> row = stockTable.row(r.getGoodsId());

            saleStockStatisticsVO.setGoodsName(r.getCommodityName());
            saleStockStatisticsVO.setGoodsCode(r.getCommodityCode());
            saleStockStatisticsVO.setStoreSaleAmount(row.getOrDefault(SaleStockTypeEnum.LS.getType(), 0));
//            saleStockStatisticsVO.setFinalStock();
            Double stockNum = goodsStockMap.getOrDefault(r.getCommodityCode(), 0D) + batchStockMap.getOrDefault(r.getCommodityCode(), 0D);
            Integer begainNum = begainMap.getOrDefault(r.getGoodsId(), 0);
            saleStockStatisticsVO.setInitialStock(begainNum + stockNum.intValue());
            saleStockStatisticsVO.setStoreSaleAmountReturn(row.getOrDefault(SaleStockTypeEnum.LS.getType(), 0));
//            saleStockStatisticsVO.setStoreSaleAmountReturnTest();
            saleStockStatisticsVO.setDistributionAmount(row.getOrDefault(SaleStockTypeEnum.PD.getType(), 0));
            saleStockStatisticsVO.setPurchaseAmount(row.getOrDefault(SaleStockTypeEnum.CD.getType(), 0));
            saleStockStatisticsVO.setSelfUseAmount(row.getOrDefault(SaleStockTypeEnum.ZD.getType(), 0));
//            saleStockStatisticsVO.setStoreSelfPurchaseSaleAmount();
            saleStockStatisticsVO.setProfitLossAmount(row.getOrDefault(SaleStockTypeEnum.SY.getType(), 0));
            return saleStockStatisticsVO;
        }).collect(Collectors.toList());
        page.setRecords(saleStockStatisticsVOS);
        return page;
    }

    /**
     * 统计全部
     *
     * @param saleStockV3Request
     * @return
     */
    public SaleStockStatisticsVO getStatisticsStatisticsSaleStockTotalRequest(StatisticsSaleStockV3Request saleStockV3Request) {
        List<String> goodsIdList = saleStockV3Request.getGoodsIdList();
        Long endTime = saleStockV3Request.getEndTime();
        Long startTime = saleStockV3Request.getStartTime();
        List<String> storeCodeList = saleStockV3Request.getStoreCodeList();
        List<SaleStock> saleStockList = getSaleStocksTotal(goodsIdList, storeCodeList, startTime, endTime);
        List<String> goodsCodeList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(goodsIdList)) {
            List<Goods> goods = goodsService.listByIds(goodsIdList);
            goodsCodeList = goods.stream().map(r -> r.getCommodityCode()).collect(Collectors.toList());
        }
        Map<Integer, List<SaleStock>> collect = saleStockList.stream().collect(Collectors.groupingBy(SaleStock::getTest));
        List<SaleStock> saleStocksTest = collect.getOrDefault(1, Lists.newArrayList());
        List<SaleStock> saleStocks = collect.getOrDefault(0, Lists.newArrayList());
        //type sale_type num
//        HashBasedTable<String, Integer, Integer> stockTable = HashBasedTable.create();
        HashMap<String, Integer> stockTable = Maps.newHashMap();
        saleStocks.forEach(r -> {
            stockTable.put(r.getType(), r.getNum());
        });
        //测试数据
        //type sale_type num
        HashMap<String, Integer> stockTableTest = Maps.newHashMap();
        saleStocksTest.forEach(r -> {
            stockTableTest.put(r.getType(), r.getNum());
        });
        //计算期初
        Long firstDayOfMonth = RebateDateUtil.getFirstDayOfMonth(startTime);
        QueryWrapper<SaleStock> queryWrapperBegin = Wrappers.<SaleStock>query().select("sum(if(sale_type=1,-num,num)) as num");
        if (CollectionUtils.isNotEmpty(goodsIdList)) {
            queryWrapperBegin.in("goods_id", goodsIdList);
        }
        if (CollectionUtils.isNotEmpty(storeCodeList)) {
            queryWrapperBegin.in("sto_code", storeCodeList);
        }
        queryWrapperBegin.between("sale_time", firstDayOfMonth, startTime);
        List<SaleStock> begainList = saleStockService.list(queryWrapperBegin);
        Integer begainNum = Optional.ofNullable(begainList).map(r -> r.get(0)).map(SaleStock::getNum).orElse(0);

//        // 连锁库存
        QueryWrapper<GaiaWmsStockH> eq = Wrappers.<GaiaWmsStockH>query().select("sum(total_qty) as total_qty").eq("stock_month", RebateDateUtil.formatMonth(startTime)).eq("stock_year", RebateDateUtil.formatYear(startTime));


        if (CollectionUtils.isNotEmpty(storeCodeList)) {
            eq.in("pro_site", storeCodeList);
        }
        if (CollectionUtils.isNotEmpty(goodsCodeList)) {
            eq.in("pro_code", goodsCodeList);
        }
        List<GaiaWmsStockH> gaiaWmsStockHList = gaiaWmsStockHService.list(eq);

        Double stockNum = 0D;
        if (CollectionUtils.isNotEmpty(gaiaWmsStockHList)) {
            stockNum = Optional.of(gaiaWmsStockHList).map(r -> r.get(0)).map(GaiaWmsStockH::getTotalQty).orElse(0D);
        }

        //门店库存
        QueryWrapper<GaiaSdStockBatchH> queryWrapper = Wrappers.<GaiaSdStockBatchH>query().select("sum(gssb_qty) as gssb_qty").eq("mat_assess_month", RebateDateUtil.formatMonth(startTime)).eq("mat_assess_year", RebateDateUtil.formatYear(startTime));
        if (CollectionUtils.isNotEmpty(goodsCodeList)) {
            queryWrapper.in("gssb_pro_id", goodsCodeList);
        }
        if (CollectionUtils.isNotEmpty(storeCodeList)) {
            queryWrapper.in("gssb_br_id", storeCodeList);
        }
        List<GaiaSdStockBatchH> gaiaSdStockBatchHList = gaiaSdStockBatchHService.list(queryWrapper);

        Double stockBatchNum = 0D;
        if (CollectionUtils.isNotEmpty(gaiaSdStockBatchHList)) {
            stockBatchNum = Optional.ofNullable(gaiaSdStockBatchHList).map(r -> r.get(0)).map(GaiaSdStockBatchH::getGssbQty).orElse(0D);
        }

//        Map<String, Double> batchStockMap = gaiaSdStockBatchHList.stream().collect(Collectors.toMap(GaiaSdStockBatchH::getGssbProId, GaiaSdStockBatchH::getGssbQty));

        SaleStockStatisticsVO saleStockStatisticsVO = new SaleStockStatisticsVO();

        saleStockStatisticsVO.setStoreSaleAmount(stockTable.getOrDefault(SaleStockTypeEnum.LS.getType(), 0));
//            saleStockStatisticsVO.setFinalStock();
        saleStockStatisticsVO.setInitialStock(begainNum + stockNum.intValue() + stockBatchNum.intValue());
//        saleStockStatisticsVO.setStoreSaleAmountReturn(stockTable.getOrDefault(SaleStockTypeEnum.LS.getType(), 0));
//            saleStockStatisticsVO.setStoreSaleAmountReturnTest();
        saleStockStatisticsVO.setDistributionAmount(-stockTable.getOrDefault(SaleStockTypeEnum.PD.getType(), 0));
        saleStockStatisticsVO.setPurchaseAmount(-stockTable.getOrDefault(SaleStockTypeEnum.CD.getType(), 0));
        saleStockStatisticsVO.setSelfUseAmount(stockTable.getOrDefault(SaleStockTypeEnum.ZD.getType(), 0));
        saleStockStatisticsVO.setLoss(-stockTable.getOrDefault(SaleStockTypeEnum.BD.getType(), 0));
//            saleStockStatisticsVO.setStoreSelfPurchaseSaleAmount();
        saleStockStatisticsVO.setProfitLossAmount(stockTable.getOrDefault(SaleStockTypeEnum.SY.getType(), 0));
        int finalStock = saleStockStatisticsVO.getInitialStock()
                + saleStockStatisticsVO.getLoss()
                + saleStockStatisticsVO.getPurchaseAmount()
                + saleStockStatisticsVO.getStoreSaleAmount()
                + saleStockStatisticsVO.getDistributionAmount()
                + saleStockStatisticsVO.getLoss()
                + saleStockStatisticsVO.getSelfUseAmount()
                + saleStockStatisticsVO.getProfitLossAmount();
        saleStockStatisticsVO.setFinalStock(finalStock);

        //测试数据
//        saleStockStatisticsVO.setStoreSaleAmountReturnTest(stockTableTest.getOrDefault(SaleStockTypeEnum.LS.getType(), 0));
        if (storeCodeList.contains("100") || storeCodeList.contains("114")) {
            saleStockStatisticsVO.setDistributionAmountTest(stockTableTest.getOrDefault(SaleStockTypeEnum.PD.getType(), 0));
        } else {
            saleStockStatisticsVO.setDistributionAmountTest(-stockTableTest.getOrDefault(SaleStockTypeEnum.PD.getType(), 0));
        }
        saleStockStatisticsVO.setStoreSaleAmountTest(stockTableTest.getOrDefault(SaleStockTypeEnum.LS.getType(), 0));


        List<WholesaleSalesRecord> list = wholesaleSalesRecordService.list();
        int sum = list.stream().map(WholesaleSalesRecord::getUsedNum).mapToInt(r -> r).sum();
        int totalNum = list.stream().map(WholesaleSalesRecord::getTotalNum).mapToInt(r -> r).sum();
        saleStockStatisticsVO.setChainInventory(totalNum - sum);

        saleStockStatisticsVO.setInitialStockTest(saleStockStatisticsVO.getInitialStock() + saleStockStatisticsVO.getChainInventory());
        int finalTestStock = saleStockStatisticsVO.getInitialStockTest() + saleStockStatisticsVO.getDistributionAmountTest() + saleStockStatisticsVO.getStoreSaleAmountTest();
        saleStockStatisticsVO.setFinalStockTest(finalTestStock);

        return saleStockStatisticsVO;
    }

    private List<SaleStock> getSaleStocksTotal(List<String> queryGoodsIdList, List<String> storeCodeList, Long startTime, Long endTime) {
//        List<SaleStock> list = saleStockService.list(Wrappers.<SaleStock>lambdaQuery().eq(SaleStock::getSaleId, 1));
//        log.info("getSaleStocks list={}", JSON.toJSONString(list));
        QueryWrapper<SaleStock> queryWrapper = Wrappers.<SaleStock>query().select("type,test,sum(if(sale_type=1,-num,num)) as num");
        if (CollectionUtils.isNotEmpty(queryGoodsIdList)) {
            queryWrapper.in("goods_id", queryGoodsIdList);
        }
        if (CollectionUtils.isNotEmpty(storeCodeList)) {
            queryWrapper.in("sto_code", storeCodeList);
        }
        queryWrapper.between("sale_time", startTime, endTime).groupBy("type,test");
        List<SaleStock> saleStockList = saleStockService.list(queryWrapper);
        log.info("统计数据 saleStockList={}", JSON.toJSONString(saleStockList));
        return saleStockList;
    }

    private List<SaleStock> getSaleStocks(List<String> queryGoodsIdList, List<String> storeCodeList, Long startTime, Long endTime) {
        List<SaleStock> list = saleStockService.list(Wrappers.<SaleStock>lambdaQuery().eq(SaleStock::getSaleId, 1));
        log.info("getSaleStocks list={}", JSON.toJSONString(list));
        QueryWrapper<SaleStock> queryWrapper = Wrappers.<SaleStock>query().select("goods_id,type,sum(if(sale_type=1,-num,num)) as num");
        if (CollectionUtils.isNotEmpty(queryGoodsIdList)) {
            queryWrapper.in("goods_id", queryGoodsIdList);
        }
        if (CollectionUtils.isNotEmpty(storeCodeList)) {
            queryWrapper.in("sto_code", storeCodeList);
        }
        queryWrapper.between("sale_time", startTime, endTime).groupBy("goods_id,type").orderByAsc("goods_id");
        List<SaleStock> saleStockList = saleStockService.list(queryWrapper);
        log.info("统计数据 saleStockList={}", JSON.toJSONString(saleStockList));
        return saleStockList;
    }

    private List<SaleStockStatisticsVO> getStatisticsSaleStockVOByTime(StatisticsSaleStockV3Request statisticsSaleStockC3Request) {
        return null;
//        List<String> goodsCodeList = statisticsSaleStockC3Request.getGoodsCode();
//        List<String> storeCodeList = statisticsSaleStockC3Request.getStoreCode();
//        Long startTime = statisticsSaleStockC3Request.getStartTime();
//        Long endTime = statisticsSaleStockC3Request.getEndTime();
//        List<String> goodsIdList = null;
//        if (CollectionUtils.isNotEmpty(goodsCodeList)) {
//            List<Goods> list = goodsService.list(Wrappers.<Goods>lambdaQuery().in(Goods::getCommodityCode, goodsCodeList));
//            goodsIdList = list.stream().map(Goods::getGoodsId).collect(Collectors.toList());
//        }
//
//        IPage page = new Page(statisticsSaleStockC3Request.getPageNo(), statisticsSaleStockC3Request.getPageSize());
//        QueryWrapper<SaleStock> select = Wrappers.<SaleStock>query()
//                .select("goods_id,type,sale_type,test,sum(num) as num ")
//                .in(CollectionUtils.isNotEmpty(goodsIdList), "goods_id", goodsIdList)
//                .ge(Objects.nonNull(startTime), "sale_time", startTime)
//                .le(Objects.nonNull(endTime), "sale_time", endTime)
//                .in(CollectionUtils.isNotEmpty(goodsIdList), "goods_id", goodsIdList)
//                .in(CollectionUtils.isNotEmpty(storeCodeList), "sto_code", storeCodeList);
//        page = saleStockService.page(page, select);
//        List<SaleStock> records = page.getRecords();
//
//        records.stream().map(r -> {
//            SaleStockStatisticsVO saleStockStatisticsVO = new SaleStockStatisticsVO();
//            Goods goods = goodsService.getById(r.getGoodsId());
//            saleStockStatisticsVO.setGoodsCode(goods.getCommodityCode());
//            saleStockStatisticsVO.setGoodsName(goods.getCommodityName());
//            String type = r.getType();
//            Integer saleType = r.getSaleType();
//            if (Objects.equals(SaleStockTypeEnum.BD.getSaleType(), type)) {
//                saleStockStatisticsVO.setLoss(-r.getNum());
//            } else if (Objects.equals(SaleStockTypeEnum.CD.getSaleType(), type)) {
//                if (Objects.equals(saleType, 1)) {
//                    saleStockStatisticsVO.setPurchaseAmount(r.getNum());
//                } else {
//                    saleStockStatisticsVO.setReturnAmount(-r.getNum());
//                }
//            } else if (Objects.equals(SaleStockTypeEnum.LS.getSaleType(), type)) {
//                if (Objects.equals(r.getTest(), 1)) {
//                    if (Objects.equals(saleType, 1)) {
//                        saleStockStatisticsVO.setStoreSaleAmountTest(-r.getNum());
//                    } else {
//                        saleStockStatisticsVO.setStoreSaleAmountReturnTest(r.getNum());
//                    }
//                } else {
//                    if (Objects.equals(saleType, 1)) {
//                        saleStockStatisticsVO.setStoreSaleAmount(-r.getNum());
//                    } else {
//                        saleStockStatisticsVO.setStoreSaleAmountReturn(r.getNum());
//                    }
//                }
//            } else if (Objects.equals(SaleStockTypeEnum.PD.getSaleType(), type)) {
//                if (Objects.equals(saleType, 1)) {
//                    saleStockStatisticsVO.setDistributionAmount(r.getNum());
//                } else {
//                    saleStockStatisticsVO.setReturnAmount(-r.getNum());
//                }
//            }
//
////            saleStockStatisticsVO.setFinalStock();
////            saleStockStatisticsVO.setInitialStock();
////            saleStockStatisticsVO.setLoss();
////            saleStockStatisticsVO.setStoreSaleAmount();
////            saleStockStatisticsVO.setDistributionAmount();
////            saleStockStatisticsVO.setReturnAmount();
////            saleStockStatisticsVO.setStoreSelfPurchaseSaleAmount();
////            saleStockStatisticsVO.setSelfUseAmount();
////            saleStockStatisticsVO.setSaleType(r.getSaleType());
////            saleStockStatisticsVO.setTest(r.getTest());
////            saleStockStatisticsVO.setNum(r.getNum());
////            return saleStockStatisticsVO;
////        }).collect(Collectors.toList());
//return null;
    }

    /**
     * 库存数量
     *
     * @param batchNo
     * @return
     */
    private Integer getStockAmount(String batchNo) {
        QueryWrapper<GaiaWmsKucen> gaiaWmsKucenLambdaQueryWrapper = Wrappers.<GaiaWmsKucen>query();
        gaiaWmsKucenLambdaQueryWrapper.select("sum(wm_kcsl) as wm_kcsl").eq(StringUtils.isNotBlank(batchNo), "wm_pch", batchNo);
        GaiaWmsKucen one = gaiaWmsKucenService.getOne(gaiaWmsKucenLambdaQueryWrapper);

        if (Objects.isNull(one)) {
            return 0;
        }
        return one.getWmKcsl();
    }

    /**
     * 采购数量
     *
     * @param batchNo
     * @return
     */
    private Integer getStockAmount4Supplier(String batchNo) {
        QueryWrapper<GaiaWmsKucen> gaiaWmsKucenLambdaQueryWrapper = Wrappers.<GaiaWmsKucen>query();
        gaiaWmsKucenLambdaQueryWrapper.select("sum(wm_kcsl) as wm_kcsl").eq(StringUtils.isNotBlank(batchNo), "wm_pch", batchNo);
        GaiaWmsKucen one = gaiaWmsKucenService.getOne(gaiaWmsKucenLambdaQueryWrapper);

        if (Objects.isNull(one)) {
            return 0;
        }
        List<WholesaleSalesRecord> list = wholesaleSalesRecordService.list(Wrappers.<WholesaleSalesRecord>lambdaQuery().eq(StringUtils.isNotBlank(batchNo), WholesaleSalesRecord::getBatchNo, batchNo));
        if (CollectionUtils.isNotEmpty(list)) {
            Integer collect = list.stream().map(r -> {
                Integer usedNum = Objects.nonNull(r.getUsedNum()) ? r.getUsedNum() : 0;
                Integer totalNum = r.getTotalNum();
                return totalNum - usedNum;
            }).mapToInt(r -> r).sum();
            return one.getWmKcsl() + collect;
        }
        return 0;
    }


    /**
     * 销售
     *
     * @param batchNo
     * @return
     */
    private Integer getSaleAmount(String batchNo) {
        QueryWrapper<SaleStock> eq = Wrappers.<SaleStock>query().select("sum(IF(sale_type = 1, num, -num)) as num").eq("batch_no", batchNo).eq("test", 0).eq("type", "sale");
        SaleStock one = saleStockService.getOne(eq);
        if (Objects.isNull(one)) {
            return 0;
        }
        return one.getNum();
    }


    /**
     * 销售供应商数据
     *
     * @param batchNo
     * @return
     */
    private Integer getSaleAmount4Supplier(String batchNo) {
        QueryWrapper<SaleStock> eq = Wrappers.<SaleStock>query().select("sum(IF(sale_type = 1, num, -num)) as num").eq("batch_no", batchNo)
//                .eq("test", 0)
                .eq("type", "sale");
        SaleStock one = saleStockService.getOne(eq);
        if (Objects.isNull(one)) {
            return 0;
        }
        return one.getNum();
    }

    /**
     * 销售供应商数据
     *
     * @return
     */
    private Integer getSaleAmount4Supplier(Long startTime, Long endTime) {
        QueryWrapper<SaleStock> eq = Wrappers.<SaleStock>query().select("sum(IF(sale_type = 1, num, -num)) as num").ge("sale_time", startTime).le("sale_time", endTime).eq("type", "sale");
        SaleStock one = saleStockService.getOne(eq);
        if (Objects.isNull(one)) {
            return 0;
        }
        return one.getNum();
    }


    /**
     * 采购数量
     *
     * @param batchNo
     * @return
     */
    private Integer getPurchaseAmount4Supplier(String batchNo) {
        GaiaBatchInfo gaiaBatchInfo = gaiaBatchInfoService.getOne(Wrappers.<GaiaBatchInfo>lambdaQuery().eq(GaiaBatchInfo::getBatBatch, batchNo));
        if (Objects.isNull(gaiaBatchInfo)) {
            return 0;
        }
        return gaiaBatchInfo.getBatReceiveQty();

    }

    /**
     * 采购数量
     *
     * @param batchNo
     * @return
     */
    private Integer getPurchaseAmount(String batchNo) {
        QueryWrapper<SaleStock> eq = Wrappers.<SaleStock>query().select("sum(IF(sale_type = 1, num, -num)) as num").eq("batch_no", batchNo).eq("type", "supplier");
        SaleStock one = saleStockService.getOne(eq);
        if (Objects.isNull(one)) {
            return 0;
        }
        return one.getNum();
    }

    /**
     * 采购数量
     *
     * @return
     */
    private Integer getPurchaseAmountBytime(Long startTime, Long endTime) {
        QueryWrapper<SaleStock> eq = Wrappers.<SaleStock>query().select("sum(num) as num").eq("type", "supplier").ge("sale_time", startTime).eq("sale_type", 1).le("sale_time", endTime);
        SaleStock one = saleStockService.getOne(eq);
        if (Objects.isNull(one)) {
            return 0;
        }
        return one.getNum();
    }
}
